package com.ymttest.utils;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import net.sf.json.JSONObject;

import com.ymt.core.tool.Logger;

/**
 * 数据处理工具
 * 
 * @author songyefeng
 *
 */
public class DataUtil {
	public static final String defaultDateString = "0001-01-01 00:00:00"; // .net中Data的默认时间
	public static final String defaultJavaDateString = "1900-01-01 00:00:00";

	@SuppressWarnings("rawtypes")
	@Deprecated
	public static void abc(Object o, String a, String b) {
		Class c = o.getClass();
		try {
			for (Field f : c.getDeclaredFields()) {
				f.setAccessible(true);
				Class type = f.getType();
				String name = f.getName();
				String get = b + ".get(\"" + name + "\")";
				if (type == String.class) {
					if (null == f.get(o)) {
						System.out.println(a + ".set" + name
								+ "(DataUtil.Stringg.getValueOrNull(" + get
								+ "));");
					} else {
						System.out.println(a + ".set" + name
								+ "(DataUtil.Stringg.getValueOrDefault(" + get
								+ ",\"" + f.get(o) + "\"));");
					}
				} else if (type == java.lang.Integer.class || type == int.class) {
					System.out.println(a + ".set" + name
							+ "(DataUtil.Integerr.GetValueOrDefault(" + get
							+ "," + f.get(o) + "));");
				} else if (type == boolean.class
						|| type == java.lang.Boolean.class) {
					System.out.println(a + ".set" + name
							+ "(DataUtil.Booleann.GetValueOrDefault(" + get
							+ "," + f.get(o) + "));");
				} else if (type == double.class
						|| type == java.lang.Double.class) {
					System.out.println(a + ".set" + name
							+ "(DataUtil.Doublee.getValueOrDefault(" + get
							+ "," + f.get(o) + "));");
				} else if (type == java.math.BigDecimal.class) {
					if (null == f.get(o)) {
						System.out.println(a + ".set" + name
								+ "(DataUtil.BigDecimall.GetValueOrNull(" + get
								+ "));");
					} else {
						System.out
								.println(a
										+ ".set"
										+ name
										+ "(DataUtil.BigDecimall.GetValueOrDefault("
										+ get + ", new BigDecimal(" + f.get(o)
										+ ")));");
					}
				}
			}
			Class fc = c.getSuperclass();
			for (Field f : fc.getDeclaredFields()) {
				f.setAccessible(true);
				Class type = f.getType();
				String name = f.getName();
				String get = b + ".get(\"" + name + "\")";
				if (type == String.class) {
					if (null == f.get(o)) {
						System.out.println(a + ".set" + name
								+ "(DataUtil.Stringg.getValueOrNull(" + get
								+ "));");
					} else {
						System.out.println(a + ".set" + name
								+ "(DataUtil.Stringg.getValueOrDefault(" + get
								+ ",\"" + f.get(o) + "\"));");
					}
				} else if (type == java.lang.Integer.class || type == int.class) {
					System.out.println(a + ".set" + name
							+ "(DataUtil.Integerr.GetValueOrDefault(" + get
							+ "," + f.get(o) + "));");
				} else if (type == boolean.class
						|| type == java.lang.Boolean.class) {
					System.out.println(a + ".set" + name
							+ "(DataUtil.Booleann.GetValueOrDefault(" + get
							+ "," + f.get(o) + "));");
				} else if (type == double.class
						|| type == java.lang.Double.class) {
					System.out.println(a + ".set" + name
							+ "(DataUtil.Doublee.getValueOrDefault(" + get
							+ "," + f.get(o) + "));");
				} else if (type == java.math.BigDecimal.class) {
					if (null == f.get(o)) {
						System.out.println(a + ".set" + name
								+ "(DataUtil.BigDecimall.GetValueOrNull(" + get
								+ "));");
					} else {
						System.out
								.println(a
										+ ".set"
										+ name
										+ "(DataUtil.BigDecimall.GetValueOrDefault("
										+ get + ", new BigDecimal(" + f.get(o)
										+ ")));");
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("rawtypes")
	public static Map<String, Object> key2Lower(Map m) {
		Map t = new HashMap();
		if (m == null) {
			return m;
		}
		Iterator it = m.keySet().iterator();
		while (it.hasNext()) {
			String key = (String) it.next();
			Object value = m.get(key);
			t.put(key.toLowerCase(), value);
		}
		return t;
	}

	/**
	 * @param o
	 *            封装数据的类
	 * @param m
	 *            数据库获取的数据
	 */
	@SuppressWarnings("rawtypes")
	public static void mapToBean(Object o, Map m) {
		try {
			BeanInfo beanInfo = Introspector.getBeanInfo(o.getClass());
			PropertyDescriptor[] propertyDescriptors = beanInfo
					.getPropertyDescriptors();
			Map t = key2Lower(m);
			// for (PropertyDescriptor property : propertyDescriptors) {
			for (int i = 0; i < propertyDescriptors.length; i++) {
				PropertyDescriptor property = propertyDescriptors[i];
				String key = property.getName().toLowerCase();

				if (t.containsKey(key)) {
					Object value = t.get(key);
					// 得到property对应的setter方法
					Method setter = property.getWriteMethod();
					Class cls = setter.getParameterTypes()[0];
					if (null != value) {
						if (value instanceof java.sql.Timestamp) {
							setter.invoke(o, String.valueOf(value));
						} else if (cls.getName() == "java.math.BigDecimal") {
							setter.invoke(o,
									new BigDecimal(String.valueOf(value)));
						} else if (cls.getTypeName() == "boolean"
								|| cls.getTypeName() == "java.lang.Boolean") {
							if (value instanceof java.lang.Integer
									&& ((int) value == 0 || (int) value == 1)) {
								setter.invoke(o, DataUtil.int2Bool((int) value));
							} else {
								setter.invoke(o, value);
							}
						} else {
							setter.invoke(o, value);
						}
					}
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("transMap2Bean Error " + e);
		}
	}

	/**
	 * 首字母转小写
	 * 
	 * @param s
	 * @return
	 */
	public static String toLowerCaseFirstOne(String s) {
		if (Character.isLowerCase(s.charAt(0)))
			return s;
		else
			return (new StringBuilder())
					.append(Character.toLowerCase(s.charAt(0)))
					.append(s.substring(1)).toString();
	}

	/**
	 * 首字母转大写
	 * 
	 * @param s
	 * @return
	 */
	public static String toUpperCaseFirstOne(String s) {
		if (Character.isUpperCase(s.charAt(0)))
			return s;
		else
			return (new StringBuilder())
					.append(Character.toUpperCase(s.charAt(0)))
					.append(s.substring(1)).toString();
	}

	public static class Json {
		@SuppressWarnings("unchecked")
		private static net.sf.json.JSONObject objFirst2Upper(
				net.sf.json.JSONObject o) {
			net.sf.json.JSONObject need = new net.sf.json.JSONObject();
			Iterator<String> it = o.keys();
			while (it.hasNext()) {
				String key = it.next();
				Object value = o.get(key);
				if (value.toString() == "null") {
					need.put(toUpperCaseFirstOne(key), value);
				} else if (value instanceof net.sf.json.JSONObject) {
					need.put(toUpperCaseFirstOne(key),
							objFirst2Upper(net.sf.json.JSONObject
									.fromObject(value)));
				} else if (value instanceof net.sf.json.JSONArray) {
					need.put(toUpperCaseFirstOne(key),
							arrFirst2Upper(net.sf.json.JSONArray
									.fromObject(value)));
				} else {
					need.put(toUpperCaseFirstOne(key), value);
				}
			}
			return need;
		}

		@SuppressWarnings("unchecked")
		private static net.sf.json.JSONObject objFirst2Lower(
				net.sf.json.JSONObject o) {
			net.sf.json.JSONObject need = new net.sf.json.JSONObject();
			Iterator<String> it = o.keys();
			while (it.hasNext()) {
				String key = it.next();
				Object value = o.get(key);
				if (value.toString() == "null") {
					need.put(toLowerCaseFirstOne(key), value);
				} else if (value instanceof net.sf.json.JSONObject) {
					need.put(toLowerCaseFirstOne(key),
							objFirst2Lower(net.sf.json.JSONObject
									.fromObject(value)));
				} else if (value instanceof net.sf.json.JSONArray) {
					need.put(toLowerCaseFirstOne(key),
							arrFirst2Lower(net.sf.json.JSONArray
									.fromObject(value)));
				} else {
					need.put(toLowerCaseFirstOne(key), value);
				}
			}
			return need;
		}

		private static net.sf.json.JSONArray arrFirst2Upper(
				net.sf.json.JSONArray arr) {
			net.sf.json.JSONArray need = new net.sf.json.JSONArray();
			for (int i = 0; i < arr.size(); i++) {
				Object t = arr.get(i);
				if (t.toString() == "null") {
					need.add(t);
				} else if (t instanceof net.sf.json.JSONObject) {
					need.add(objFirst2Upper(net.sf.json.JSONObject
							.fromObject(t)));
				} else if (t instanceof net.sf.json.JSONArray) {
					need.add(arrFirst2Upper(net.sf.json.JSONArray.fromObject(t)));
				} else {
					need.add(t);
				}
			}
			return need;
		}

		private static net.sf.json.JSONArray arrFirst2Lower(
				net.sf.json.JSONArray arr) {
			net.sf.json.JSONArray need = new net.sf.json.JSONArray();
			for (int i = 0; i < arr.size(); i++) {
				Object t = arr.get(i);
				if (t.toString() == "null") {
					need.add(t);
				} else if (t instanceof net.sf.json.JSONObject) {
					need.add(objFirst2Lower(net.sf.json.JSONObject
							.fromObject(t)));
				} else if (t instanceof net.sf.json.JSONArray) {
					need.add(arrFirst2Lower(net.sf.json.JSONArray.fromObject(t)));
				} else {
					need.add(t);
				}
			}
			return need;
		}

		/**
		 * json字符串的所有key的首字母转为大写
		 * 
		 * @param o
		 * @return
		 */
		public static net.sf.json.JSONArray parseJsonArray(Object o) {
			net.sf.json.JSONArray need = new net.sf.json.JSONArray();
			net.sf.json.JSONArray obj = net.sf.json.JSONArray.fromObject(o);
			for (int i = 0; i < obj.size(); i++) {
				Object t = obj.get(i);
				if (t instanceof net.sf.json.JSONObject) {
					need.add(parseJsonObj(t));
				} else if (t instanceof net.sf.json.JSONArray) {
					need.add(parseJsonArray(o));
				}
			}
			return need;
		}

		/**
		 * json字符串的所有key的首字母转为小写
		 * 
		 * @param o
		 * @return
		 */
		public static net.sf.json.JSONArray parseJsonArray2(Object o) {
			net.sf.json.JSONArray need = new net.sf.json.JSONArray();
			net.sf.json.JSONArray obj = net.sf.json.JSONArray.fromObject(o);
			for (int i = 0; i < obj.size(); i++) {
				Object t = obj.get(i);
				if (t instanceof net.sf.json.JSONObject) {
					need.add(parseJsonObj2(t));
				} else if (t instanceof net.sf.json.JSONArray) {
					need.add(parseJsonArray2(o));
				}
			}
			return need;
		}

		/**
		 * json字符串的所有key的首字母转为大写
		 * 
		 * @param o
		 * @return
		 */
		@SuppressWarnings("unchecked")
		public static net.sf.json.JSONObject parseJsonObj(Object o) {
			net.sf.json.JSONObject need = new net.sf.json.JSONObject();
			net.sf.json.JSONObject obj = net.sf.json.JSONObject.fromObject(o);
			Iterator<String> it = obj.keys();
			while (it.hasNext()) {
				String key = it.next();
				Object value = obj.get(key);
				if (value.toString() == "null") {
					need.put(toUpperCaseFirstOne(key), value);
				} else if (value instanceof net.sf.json.JSONObject) {
					need.put(toUpperCaseFirstOne(key),
							objFirst2Upper(net.sf.json.JSONObject
									.fromObject(value)));
				} else if (value instanceof net.sf.json.JSONArray) {
					need.put(toUpperCaseFirstOne(key),
							arrFirst2Upper(net.sf.json.JSONArray
									.fromObject(value)));
				} else {
					need.put(toUpperCaseFirstOne(key), value);
				}
			}
			return need;
		}

		/**
		 * json字符串的所有key的首字母转为小写
		 * 
		 * @param o
		 * @return
		 */
		@SuppressWarnings("unchecked")
		public static net.sf.json.JSONObject parseJsonObj2(Object o) {
			net.sf.json.JSONObject need = new net.sf.json.JSONObject();
			net.sf.json.JSONObject obj = net.sf.json.JSONObject.fromObject(o);
			Iterator<String> it = obj.keys();
			while (it.hasNext()) {
				String key = it.next();
				Object value = obj.get(key);
				if (value.toString() == "null") {
					need.put(toLowerCaseFirstOne(key), value);
				} else if (value instanceof net.sf.json.JSONObject) {
					need.put(toLowerCaseFirstOne(key),
							objFirst2Lower(net.sf.json.JSONObject
									.fromObject(value)));
				} else if (value instanceof net.sf.json.JSONArray) {
					need.put(toLowerCaseFirstOne(key),
							arrFirst2Lower(net.sf.json.JSONArray
									.fromObject(value)));
				} else {
					need.put(toLowerCaseFirstOne(key), value);
				}
			}
			return need;
		}

		/**
		 * JSONObject排序
		 * 
		 * @param obj
		 * @return
		 */
		@SuppressWarnings("all")
		public static JSONObject sortJsonObject(Object object) {
			net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject
					.fromObject(object);
			Map map = new TreeMap();
			Iterator<String> it = jsonObject.keys();
			while (it.hasNext()) {
				String key = it.next();
				Object value = jsonObject.get(key);
				if (null == value || value.toString().equals("null")) {
					map.put(key, value);
				} else if (value instanceof net.sf.json.JSONObject) {
					map.put(key, sortJsonObject(net.sf.json.JSONObject
							.fromObject(value)));
				} else if (value instanceof net.sf.json.JSONArray) {
					map.put(key, sortJsonArray(net.sf.json.JSONArray
							.fromObject(value)));
				} else {
					map.put(key, value);
				}
			}
			return net.sf.json.JSONObject.fromObject(map);
		}

		/**
		 * JSONArray排序
		 * 
		 * @param array
		 * @return
		 */
		@SuppressWarnings("all")
		public static net.sf.json.JSONArray sortJsonArray(Object arrayObject) {
			net.sf.json.JSONArray array = net.sf.json.JSONArray
					.fromObject(arrayObject);
			List list = new ArrayList();
			int size = array.size();
			for (int i = 0; i < size; i++) {
				Object obj = array.get(i);
				if (null == obj || obj.toString().equals("null")) {
					list.add(obj);
				} else if (obj instanceof net.sf.json.JSONObject) {
					list.add(sortJsonObject(net.sf.json.JSONObject
							.fromObject(obj)));
				} else if (obj instanceof net.sf.json.JSONArray) {
					list.add(sortJsonArray(net.sf.json.JSONArray
							.fromObject(obj)));
				} else {
					list.add(obj);
				}
			}

			list.sort((o1, o2) -> o1.toString().compareTo(o2.toString()));
			return net.sf.json.JSONArray.fromObject(list);
		}

		/**
		 * 对JSONArray做比较：size不同，返回false; 排序后的String对比，不相同返回false;
		 * 
		 * @param expect_object
		 * @param actual_object
		 * @return
		 */
		public static boolean compareJsonArray(Object expect_object,
				Object actual_object) {
			net.sf.json.JSONArray expect = net.sf.json.JSONArray
					.fromObject(expect_object);
			net.sf.json.JSONArray actual = net.sf.json.JSONArray
					.fromObject(actual_object);
			int expect_size = expect.size();
			int actual_size = actual.size();
			if (expect_size != actual_size) {
				return false;
			}
			if (sortJsonArray(expect).equals(sortJsonArray(actual)) == false) {
				return false;
			}
			return true;
		}

		/**
		 * 对JSONObject做比较：排序后的String对比，不相同返回false;
		 * 
		 * @param expect_object
		 * @param actual_object
		 * @return
		 */
		public static boolean compareJsonObject(Object expect_object,
				Object actual_object) {
			net.sf.json.JSONObject expect = net.sf.json.JSONObject
					.fromObject(expect_object);
			net.sf.json.JSONObject actual = net.sf.json.JSONObject
					.fromObject(actual_object);
			if (!sortJsonObject(expect).toString().equals(
					sortJsonObject(actual).toString())) {
				return false;
			}
			return true;
		}

	}

	public static class KeyValuePair<K, V> {
		private K key;
		private V value;

		public KeyValuePair() {
		}

		public KeyValuePair(K key, V value) {
			this.key = key;
			this.value = value;
		}

		public K getKey() {
			return key;
		}

		public void setKey(K key) {
			this.key = key;
		}

		public V getValue() {
			return value;
		}

		public void setValue(V value) {
			this.value = value;
		}

	}

	public static class Doublee {
		public static java.lang.Double getValueOrDefault(Object o) {
			if (o == null) {
				return 0d;
			}
			return (Double) o;
		}

		public static java.lang.Double getValueOrDefault(Object o,
				Object defaultValue) {
			if (o == null) {
				return (Double) defaultValue;
			}
			return (Double) o;
		}

		public static java.lang.Double getValueOrNull(Object o) {
			if (o == null) {
				return null;
			}
			return (Double) o;
		}

	}

	public static class Stringg {
		public static boolean IsNullOrWhiteSpace(Object o) {
			if (null == o) {
				return true;
			}
			java.lang.String s = java.lang.String.valueOf(o);
			if (s.trim().length() == 0) {
				return true;
			}
			return false;
		}

		public static java.lang.String getValueOrDefault(Object o) {
			if (null == o) {
				return Empty;
			}
			return java.lang.String.valueOf(o);
		}

		public static java.lang.String getValueOrDefault(Object o,
				String defaultValue) {
			if (null == o) {
				return defaultValue;
			}
			return java.lang.String.valueOf(o);
		}

		public static java.lang.String getValueOrNull(Object o) {
			if (null == o) {
				return null;
			}
			return java.lang.String.valueOf(o);
		}

		public static boolean isNullOrEmpty(Object o) {
			if (null == o) {
				return true;
			}
			java.lang.String s = java.lang.String.valueOf(o);
			if (s.length() == 0) {
				return true;
			}
			return false;
		}

		public static java.lang.String Empty = "";
	}

	public static class Integerr {

		/**
		 * 如果传入的Integer值为null，则返回0；否则返回原值
		 * 
		 * @param value
		 * @return
		 */
		public static java.lang.Integer GetValueOrDefault(Object value) {
			if (null == value) {
				return 0;
			}
			return (java.lang.Integer) value;
		}

		/**
		 * 如果传入的Integer值为null，则返回defaultValue；否则返回原值
		 * 
		 * @param value
		 * @return
		 */
		public static java.lang.Integer GetValueOrDefault(Object value,
				Object defaultValue) {
			if (null == value) {
				return (java.lang.Integer) defaultValue;
			}
			return (java.lang.Integer) value;
		}

		public static java.lang.Integer GetValueOrNull(Object value) {
			if (null == value) {
				return null;
			}
			return (java.lang.Integer) value;
		}
	}

	public static Boolean isBiggerThan(BigDecimal source, BigDecimal compareTo) {

		if (source == null) {
			source = BigDecimal.ZERO;
		}
		if (source.compareTo(compareTo) > 0) {
			return true;
		} else if (source.compareTo(compareTo) == 0) {
			return null;
		} else {
			return false;
		}
	}

	public static boolean isEqualZero(BigDecimal source) {
		return isEqual(source, BigDecimal.ZERO);
	}

	public static boolean isEqual(BigDecimal source, BigDecimal compareTo) {
		if (source == null) {
			source = BigDecimal.ZERO;
		}
		if (source.compareTo(compareTo) == 0) {
			return true;
		}
		return false;
	}

	public static class BigDecimall {
		/**
		 * 如果传入的BigDecimal值为null，则返回0；否则返回原值
		 * 
		 * @param value
		 * @return
		 */
		public static java.math.BigDecimal GetValueOrDefault(Object value) {
			if (null == value) {
				return new java.math.BigDecimal(0);
			}
			return (java.math.BigDecimal) value;
		}

		/**
		 * 如果传入的BigDecimal值为null，则返回0；否则返回原值
		 * 
		 * @param value
		 * @return
		 */
		public static java.math.BigDecimal GetValueOrDefault(Object value,
				Object defaultValue) {
			if (null == value) {
				return (java.math.BigDecimal) defaultValue;
			}
			return (java.math.BigDecimal) value;
		}

		/**
		 * x+y
		 * 
		 * @param x
		 * @param y
		 * @return
		 */
		public static BigDecimal add(BigDecimal x, BigDecimal y) {
			return GetValueOrDefault(x).add(GetValueOrDefault(y));
		}

		public static int compare(BigDecimal x, BigDecimal y) {
			return GetValueOrDefault(x).compareTo(GetValueOrDefault(y));
		}

		public static int compare0(BigDecimal x) {
			return compare(x, new BigDecimal(0));
		}

		/**
		 * x-y
		 * 
		 * @param x
		 * @param y
		 * @return
		 */
		public static BigDecimal subtract(BigDecimal x, BigDecimal y) {
			return GetValueOrDefault(x).subtract(GetValueOrDefault(y));
		}

		public static java.math.BigDecimal GetValueOrNull(Object value) {
			if (null == value) {
				return null;
			}
			return (java.math.BigDecimal) value;
		}

		public static String format(DecimalFormat df, Object value) {
			if (null == value) {
				return null;
			}
			return df.format(value);
		}

		public static String format(String formatString, Object value) {
			if (null == value) {
				return null;
			}
			DecimalFormat df = new DecimalFormat(formatString);
			return df.format(value);
		}

		/**
		 * 如果传入的BigDecimal值为null，则返回默认值0；否则返回原值
		 * 
		 * @param value
		 * @param defalt
		 * @return
		 */
		public static java.math.BigDecimal GetValueOrDefault(BigDecimal value,
				BigDecimal defalt) {
			if (null == value) {
				return defalt;
			}
			return value;
		}
	}

	public static class Booleann {

		/**
		 * 如果传入的Boolean值为null，则返回false；否则返回原值
		 * 
		 * @param obj
		 * @return
		 */
		public static boolean GetValueOrDefault(Object obj) {
			if (null == obj) {
				return false;
			}
			return (boolean) obj;
		}

		public static Boolean GetValueOrDefault(Object obj, Object defaultValue) {
			if (null == obj) {
				return (Boolean) defaultValue;
			}
			return (Boolean) obj;
		}

		public static Boolean GetValueOrNull(Object obj) {
			if (null == obj) {
				return null;
			}
			return (boolean) obj;
		}
	}

	/**
	 * 尽量模仿C#的TimeSpan
	 * 
	 * @author songyefeng
	 *
	 */
	public static class TimeSpan {
		private int day;
		private int hour;
		private int minute;
		private int second;
		private long timeMillis;

		public TimeSpan(long timeMillis) {
			this.timeMillis = timeMillis;
			parseToDHMS(timeMillis);
		}

		private void parseToDHMS(long timeMillis) {
			this.day = (int) (timeMillis / 1000 / 60 / 60 / 24);
			long hmsTimeMillis = timeMillis - this.day * 1000 * 60 * 60 * 24;
			this.hour = (int) (hmsTimeMillis / 1000 / 60 / 60);
			this.minute = (int) ((hmsTimeMillis / 1000 - this.hour * 60 * 60) / 60);
			this.second = (int) (hmsTimeMillis / 1000 - this.hour * 60 * 60 - this.minute * 60);
		}

		/**
		 * 转换为day.hour:minute:second的字符串
		 * 
		 * @param timeMillis
		 */
		public String toTimeSpanString(long timeMillis) {
			parseToDHMS(timeMillis);
			return toString();
		}

		public static long toTimeMillis(int day, int hour, int minute,
				int second) {
			long result = 0l;
			result += day * 1000 * 60 * 60 * 24;
			result += hour * 1000 * 60 * 60;
			result += minute * 1000 * 60;
			result += second * 1000;
			return result;
		}

		public static long toTimeMillis(String timeSpan) {
			int day, hour, minute, second;
			if (timeSpan == null) {
				return 0;
			}
			if (timeSpan.contains(".")) {
				String[] arr = timeSpan.split("\\.");
				day = Integer.valueOf(arr[0]);
				String[] arr1 = arr[1].split(":");
				hour = Integer.valueOf(arr1[0]);
				minute = Integer.valueOf(arr1[1]);
				second = Integer.valueOf(arr1[2]);
			} else {
				day = 0;
				String[] arr1 = timeSpan.split(":");
				hour = Integer.valueOf(arr1[0]);
				minute = Integer.valueOf(arr1[1]);
				second = Integer.valueOf(arr1[2]);
			}
			return toTimeMillis(day, hour, minute, second);
		}

		public int getDay() {
			return day;
		}

		public void setDay(int day) {
			this.day = day;
		}

		public int getHour() {
			return hour;
		}

		public void setHour(int hour) {
			this.hour = hour;
		}

		public int getMinute() {
			return minute;
		}

		public void setMinute(int minute) {
			this.minute = minute;
		}

		public int getSecond() {
			return second;
		}

		public void setSecond(int second) {
			this.second = second;
		}

		public long getTimeMillis() {
			return timeMillis;
		}

		public void setTimeMillis(long timeMillis) {
			this.timeMillis = timeMillis;
		}

		public String toString() {
			String hms = fillLengthStartWith0(String.valueOf(this.hour), 2)
					+ ":"
					+ fillLengthStartWith0(String.valueOf(this.minute), 2)
					+ ":"
					+ fillLengthStartWith0(String.valueOf(this.second), 2);
			if (this.day == 0) {
				return hms;
			}
			return this.day + "." + hms;
		}

	}

	/**
	 * 保留2位小数
	 * 
	 * @param obj
	 * @return
	 */
	public static String retain2Decimal(Object obj) {
		if (null == obj || "null".equals(java.lang.String.valueOf(obj))) {
			return null;
		}
		DecimalFormat format = new DecimalFormat("#0.00");
		return format.format(obj);
	}

	public static void verify(Object expected, Object actual, String desc) {
		if (expected instanceof java.math.BigDecimal) {
			verifyDecimalEquals(expected, actual, desc);
		} else {
			verifyEquals(expected, actual, desc);
		}
	}

	public static void verifyEquals(Object expected, Object actual, String desc) {
		if (null == expected) {
			expected = "null";
		}
		if (null == actual) {
			actual = "null";
		}
		Logger.verifyEquals(java.lang.String.valueOf(expected),
				java.lang.String.valueOf(actual), desc);
	}

	public static void verifyDecimalEquals(Object expected, Object actual,
			String desc) {
		Object exp;
		Object act;

		if (null == expected) {

			exp = BigDecimal.ZERO.setScale(2);

		} else {
			exp = BigDecimall.format("0.00", expected);
		}

		if (null == actual) {
			act = BigDecimal.ZERO.setScale(2);

		} else {
			act = BigDecimall.format("0.00", actual);
		}
		verifyEquals(exp, act, desc);
	}
	public static void verifyDateEquals(Object expected, Object actual,
			String desc) {
		String exp = "null";
		String act = "null";
		if (null != expected) {
			exp = YMTDateUtil.parseRespDate2(String.valueOf(expected));
			// java的最小时间是defaultJavaDateString, .net最小时间是defaultDateString,
			// 由于接口java化，所以统一转成java时间
			if (exp.equals(defaultDateString)) {
				exp = defaultJavaDateString;
			}
		}
		if (null != actual) {
			act = YMTDateUtil.parseRespDate2(String.valueOf(actual));
			if (act.equals(defaultDateString)) {
				act = defaultJavaDateString;
			}
		}

		verifyEquals(exp, act, desc);
	}

	/**
	 * 时间相似度
	 * 
	 * @param expected
	 * @param actual
	 * @param diffMills
	 *            允许的差值，单位：毫秒
	 * @param desc
	 */
	public static void verifyDateNearlyEquals(Object expected, Object actual,
			long diffMills, String desc) {
		String exp = "null";
		String act = "null";
		long expLong = 0l;
		long actLong = 0l;
		if (null != expected) {
			exp = YMTDateUtil.parseRespDate2(String.valueOf(expected));
			expLong = YMTDateUtil.date2TimeStamp(exp);
		}
		if (null != actual) {
			act = YMTDateUtil.parseRespDate2(String.valueOf(actual));
			actLong = YMTDateUtil.date2TimeStamp(act);
		}
		long diff = expLong - actLong;
		if (diff > diffMills || diff < (-1 * diffMills)) {
			verifyEquals(exp, act, desc + ", 相差了" + diff + "毫秒");
		}
	}

	/**
	 * 判断对象是否是null，或者是空的容器
	 * 
	 * @param lst
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static boolean isNullOrEmpty(Object array) {
		Object[] objs = null;
		if (null == array) {
			return true;
		}
		if (array instanceof List) {
			objs = ((List) array).toArray();
		} else {
			objs = (Object[]) array;
		}
		if (objs.length == 0) {
			return true;
		}
		return false;
	}

	/**
	 * boolean转int, true=1, false=0
	 * 
	 * @param isTrue
	 * @return
	 */
	public static int bool2Int(boolean isTrue) {
		int temp = isTrue ? 1 : 0;
		return temp;
	}

	/**
	 * boolean转int, true=1, false=0
	 * 
	 * @param isTrue
	 * @return
	 */
	public static Integer booltoInt(Boolean isTrue) {
		if (isTrue == null) {
			return null;
		}
		int temp = isTrue ? 1 : 0;
		return temp;
	}

	/**
	 * int转boolean
	 * 
	 * @param i
	 * @return
	 */
	public static boolean int2Bool(int i) {
		if (i == 0) {
			return false;
		}
		return true;
	}

	/**
	 * 不带单引号
	 * 
	 * @param array
	 * @return
	 */
	public static String toInOfSql2(Object array) {
		return toInOfSql(array).replaceAll("'", "");
	}

	/**
	 * list或者array转成sql查询中in的查询条件
	 * 
	 * @param list
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static String toInOfSql(Object array) {
		Object[] objs;
		if (array instanceof List) {
			objs = ((List) array).toArray();
		} else {
			objs = (Object[]) array;
		}
		StringBuffer sb = new StringBuffer();
		sb.append("(");
		for (int i = 0; i < objs.length; i++) {
			sb.append("'" + objs[i] + "'");
			if (i < objs.length - 1) {
				sb.append(", ");
			}
		}
		sb.append(")");
		return sb.toString();
	}

	/**
	 * 根据长度在前面补0
	 * 
	 * @param orignal
	 * @param length
	 * @return
	 */
	public static String fillLengthStartWith0(String orignal, int length) {
		int len_minu;
		StringBuffer sb = new StringBuffer();
		len_minu = length - orignal.length();
		if (len_minu > 0) {
			for (int i = 0; i < len_minu; i++) {
				sb.append("0");
			}
			orignal = sb + orignal;
		}
		return orignal;
	}

	public static class Random {
		/**
		 * 
		 * @param min
		 * @param max
		 * @return
		 */
		public static int getRandomIntFromRange(int min, int max) {
			int v = 0;
			v = (int) (Math.random() * max);
			while (v < min) {
				v = (int) (Math.random() * max);
			}
			return v;
		}
	}

	public static class SQL {
		/**
		 * 为存储过程声明变量
		 * 
		 * @param type
		 *            </br> dt=datetime </br> i=int </br> ti=tinyint </br> b=bit
		 *            </br> nv=nvarchar
		 * @param sb
		 * @param var
		 *            变量名
		 * @param value
		 *            变量值
		 */
		public static void declareVarOfSp(String type, StringBuilder sb,
				String var, Object value) {
			if (type.equalsIgnoreCase("dt")) {
				addDatetime(sb, var, value);
			} else if (type.equalsIgnoreCase("i")) {
				addInt(sb, var, value);
			} else if (type.equalsIgnoreCase("ti")) {
				addTinyint(sb, var, value);
			} else if (type.equalsIgnoreCase("b")) {
				addBit(sb, var, value);
			} else if (type.equalsIgnoreCase("nv")) {
				addNvarchar(sb, var, value);
			}
			sb.append("; \n");
		}

		private static void addNvarchar(StringBuilder sb, String var,
				Object value) {
			if (null == value) {
				sb.append(" declare @" + var + " nvarchar(128) = null");
			} else {
				sb.append(" declare @" + var + " nvarchar(128) = '" + value
						+ "'");
			}
		}

		private static void addDatetime(StringBuilder sb, String var,
				Object value) {
			if (null == value) {
				sb.append(" declare @" + var + " datetime = null");
			} else {
				sb.append(" declare @" + var + " datetime = '" + value + "'");
			}
		}

		private static void addInt(StringBuilder sb, String var, Object value) {
			if (null == value) {
				sb.append(" declare @" + var + " int = null");
			} else {
				sb.append(" declare @" + var + " int = " + value);
			}
		}

		private static void addBit(StringBuilder sb, String var, Object value) {
			if (null == value) {
				sb.append(" declare @" + var + " bit = null");
			} else {
				sb.append(" declare @" + var + " bit = " + value);
			}
		}

		private static void addTinyint(StringBuilder sb, String var,
				Object value) {
			if (null == value) {
				sb.append(" declare @" + var + " tinyint = null");
			} else {
				sb.append(" declare @" + var + " tinyint = " + value);
			}
		}
	}

	public static String getObjectPropertyVerifyString(String desc,
			String fieldName) {
		return String.format("验证%s.%s", desc, fieldName);
	}

	public static void verifyObject(Object expect, Object actual, String desc) {
		Class<?> clazz = expect.getClass();
		Field[] fields = clazz.getDeclaredFields();
		for (Field field : fields) {
			Class<?> fieldType = field.getType();
			String field_type_simpleName = fieldType.getSimpleName(); //字段名
			String field_type_fullName = fieldType.getName(); //字段包+字段名
			try {
				if ("boolean".equals(field_type_simpleName)) {
					Method method = clazz.getMethod("is"
							+ toUpperCaseFirstOne(field.getName()));
					verify(method.invoke(expect),
							method.invoke(actual),
							getObjectPropertyVerifyString(desc, field.getName()));
				} else if ("BigDecimal".equals(field_type_simpleName)
						|| "Integer".equals(field_type_simpleName)
						|| "String".equals(field_type_simpleName)
						|| "int".equals(field_type_simpleName)
						|| "Date".equals(field_type_simpleName)
						|| "double".equalsIgnoreCase(field_type_simpleName)
						|| "long".equalsIgnoreCase(field_type_simpleName)
						|| "float".equalsIgnoreCase(field_type_simpleName)
						|| "char".equals(field_type_simpleName)
						|| "Boolean".equals(field_type_simpleName)) {
					Method method = clazz.getMethod("get"
							+ toUpperCaseFirstOne(field.getName()));
					verify(method.invoke(expect),
							method.invoke(actual),
							getObjectPropertyVerifyString(desc, field.getName()));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			//			System.out.println(field.getType().getSimpleName()+">>"+field.getName());
		}
	}

	public static void main(String[] args) {
		/*		System.out.println(new TimeSpan(10779000l));
				System.out.println(TimeSpan.toTimeMillis(1, 1, 1, 1));
				System.out.println(TimeSpan.toTimeMillis("1:01:01:01"));
				Object i = null;
				System.out.println(i instanceof Object);
				System.out.println("compare>>"
						+ DataUtil.BigDecimall.compare(new BigDecimal(1),
								new BigDecimal(0.00)));
				System.out.println(new BigDecimal(0.09).setScale(2,
						BigDecimal.ROUND_FLOOR));
				Object o1 = Json
						.sortJsonObject("{\"OrderNo\":112495536,\"LeaveWord\":\"autotest\",\"AddTime\":\"2016-12-19T11:50:28.117\",\"OrderState\":16,\"RiskVerifiedStatus\":0,\"IsPaidInFull\":false,\"BuyerLoginId\":\"autotest_Dw8x9EvLqS\",\"BuyerPhone\":\"13100000001\",\"BuyerName\":\"\",\"ReceivePerson\":\"李四\",\"ReceiveEmail\":\"tCj3lEq3Ogzt@163.com\",\"ProductSku\":\"1234567\",\"ProductCode\":\"1234567\",\"TotalPrice\":343.67,\"BondedAreaId\":2,\"Phone\":\"13100000001\",\"Telephone\":\"021-51002100\",\"OrderNote\":\"\",\"ReceiverCertificateNo\":\"\",\"Province\":\"上海市闸北区灵石路636号\",\"City\":\"\",\"County\":\"\",\"Address\":\"上海市闸北区灵石路636号\",\"PostCode\":\"200001\",\"ProductName\":\"自动化测试商品\",\"ProductNo\":\"5818e906-431b-4d19-86d9-bd3cb8e0e423\",\"CatalogInfo\":\"\",\"CatalogId\":\"1873cc19-45ce-4e12-8bf9-8b8127d2ab22\",\"BondedArea\":\"宁波保税区\",\"ProductRegisterNo\":\"123456\",\"ProductNum\":4,\"ProductPrice\":26.00,\"PayType\":\"支付宝\",\"PaySerialNo\":\"14145593\",\"Freight\":23.00,\"ExpressCompany\":\"\",\"SellerCouponAmount\":0.0}");
				Object o2 = Json
						.sortJsonObject("{\"address\":\"上海市闸北区灵石路636号\",\"addTime\":\"2016-12-19T11:12:17\",\"bondedArea\":\"\",\"bondedAreaId\":0,\"buyerLoginId\":\"autotest_Dw8x9EvLqS\",\"buyerName\":\"\",\"buyerPhone\":\"13100000001\",\"catalogId\":\"6fe127f4-a52d-482d-93a8-19f1b9ff4de1\",\"catalogInfo\":\"6:红色\",\"city\":\"\",\"county\":\"\",\"expressCompany\":\"\",\"freight\":21.00,\"isPaidInFull\":true,\"leaveWord\":\"ymt autotest\",\"orderNo\":112495508,\"orderNote\":null,\"orderState\":4,\"paySerialNo\":\"\",\"payType\":null,\"phone\":\"13100000001\",\"postCode\":\"200001\",\"productCode\":null,\"productName\":\"自动化测试商品\",\"productNo\":\"fa7e7d48-ecb9-4b61-aec6-d3a5ec10324e\",\"productNum\":3,\"productPrice\":210.00,\"productRegisterNo\":\"\",\"productSku\":null,\"province\":\"上海市闸北区灵石路636号\",\"receiveEmail\":\"tCj3lEq3Ogzt@163.com\",\"receivePerson\":\"李四\",\"receiverCertificateNo\":null,\"riskVerifiedStatus\":0,\"sellerCouponAmount\":null,\"telephone\":\"021-51002100\",\"totalPrice\":0.00,\"paidInFull\":true}");
				System.out.println(o1);
				System.out.println(o2);

				Object o3 = DataUtil.Json
						.parseJsonObj2("{\"Code\":200,\"BCode\":0,\"Msg\":null,\"Data\":{\"Orders\":[{\"Basic\":{\"ID\":112507901,\"CreatedTime\":\"2017-01-09T15:30:24.523\",\"CancelledTime\":null,\"AcceptedTime\":null,\"Source\":\"APP\",\"Type\":0,\"Status\":1,\"TotalPrice\":50.00,\"Discount\":0.00,\"PreSaleOrder\":false},\"Buyer\":{\"NickName\":\"autotest_Dw8x9EvLqS\",\"Message\":\"ymt autotest\",\"ID\":\"20238699\",\"LoginId\":\"autotest_Dw8x9EvLqS\",\"Email\":\"tCj3lEq3Ogzt@163.com\"},\"Seller\":{\"Comment\":null,\"ID\":\"3383\",\"LoginId\":\"wesper\",\"Email\":\"1wwwwww@126.com\"},\"Consignee\":{\"Name\":\"李四\",\"Address\":\"上海市闸北区灵石路636号\",\"Postcode\":\"200001\",\"Phone\":\"13100000001\",\"Tel\":\"021-51002100\"},\"Products\":[{\"Name\":\"自动化测试商品\",\"Categories\":[111111111,22222222,3333333],\"SKU\":null,\"Price\":10.00,\"Count\":5,\"TotalPrice\":50.00,\"PropertyInfo\":\"06f25e0c-e431-44ae-8a07-4d0bc824e3bd#尺寸:951a814e-2ded-4241-b9a0-91b2cd9a44fd#6,d2f663ea-3214-4344-abce-a8eaffcc43ce#颜色:f3ed3ad7-a084-450b-b698-256542963306#红色\",\"BondedArea\":0,\"Logistics\":3,\"OriginalPrice\":10.00,\"PartialFreight\":21.00,\"PartialYmtCoupon\":1.00,\"PartialSellerCoupon\":0.00,\"PartialDiscount\":0.00,\"PartialSellerPromotion\":0.00,\"RefundInfo\":null,\"BrandId\":5,\"PreSale\":false,\"ThirdPartyDiscount\":0.0,\"CatalogId\":\"eabfd881-5534-4a30-a7c7-8181c4ce09d6\",\"ProductId\":\"b9de37bc-6816-47b4-944c-c9cfa4ac9645\",\"CatalogType\":0,\"PackageNo\":\"11111111\",\"ActivityId\":0}],\"Payment\":{\"ActualPaid\":-21.00,\"Details\":null,\"Summary\":{\"OrderId\":112507901,\"PaidCash\":0.00,\"PaidGift\":0.00,\"PaidFreeCard\":0.00,\"PaidYmtCoupon\":1.00,\"PaidSellerCoupon\":0.00,\"PostPaidCash\":0.00,\"PostPaidGift\":0.00,\"TotalThirdPartyDiscount\":0.0,\"TotalProductPrice\":50.00,\"FirstPayProductPrice\":50.00,\"Freight\":21.00,\"OrderDiscount\":0.00,\"PostPayDiscount\":0.00,\"TotalRefundedCash\":null,\"TotalRefundedGift\":null,\"TotalRefundedYmtCoupon\":null,\"TotalActivityPrice\":0.00,\"TotalCanceledCash\":null,\"TotalCanceledYmtCoupon\":null,\"TotalRefundedThirdPartyDiscount\":0.0}},\"Transfer\":{\"DeliveredTime\":null,\"ReceiptConfirmedTime\":null}},{\"Basic\":{\"ID\":112507902,\"CreatedTime\":\"2017-01-09T15:30:24.737\",\"CancelledTime\":null,\"AcceptedTime\":null,\"Source\":\"APP\",\"Type\":0,\"Status\":2,\"TotalPrice\":10.00,\"Discount\":0.00,\"PreSaleOrder\":false},\"Buyer\":{\"NickName\":\"autotest_Dw8x9EvLqS\",\"Message\":\"ymt autotest\",\"ID\":\"20238699\",\"LoginId\":\"autotest_Dw8x9EvLqS\",\"Email\":\"tCj3lEq3Ogzt@163.com\"},\"Seller\":{\"Comment\":null,\"ID\":\"3383\",\"LoginId\":\"wesper\",\"Email\":\"1wwwwww@126.com\"},\"Consignee\":{\"Name\":\"李四\",\"Address\":\"上海市闸北区灵石路636号\",\"Postcode\":\"200001\",\"Phone\":\"13100000001\",\"Tel\":\"021-51002100\"},\"Products\":[{\"Name\":\"自动化测试商品\",\"Categories\":[111111111,22222222,3333333],\"SKU\":null,\"Price\":10.00,\"Count\":1,\"TotalPrice\":10.00,\"PropertyInfo\":\"06f25e0c-e431-44ae-8a07-4d0bc824e3bd#尺寸:951a814e-2ded-4241-b9a0-91b2cd9a44fd#6,d2f663ea-3214-4344-abce-a8eaffcc43ce#颜色:f3ed3ad7-a084-450b-b698-256542963306#红色\",\"BondedArea\":0,\"Logistics\":3,\"OriginalPrice\":10.00,\"PartialFreight\":21.00,\"PartialYmtCoupon\":1.00,\"PartialSellerCoupon\":0.00,\"PartialDiscount\":0.00,\"PartialSellerPromotion\":0.00,\"RefundInfo\":null,\"BrandId\":5,\"PreSale\":false,\"ThirdPartyDiscount\":0.0,\"CatalogId\":\"4bb65eea-d0a4-4661-a8a1-08860ccbb6db\",\"ProductId\":\"57f204c5-1d06-4b47-8111-02dc326048d7\",\"CatalogType\":0,\"PackageNo\":\"11111111\",\"ActivityId\":0}],\"Payment\":{\"ActualPaid\":9.00,\"Details\":[{\"Type\":1,\"PaidTime\":\"2017-01-09T15:30:27.71\",\"InternalTradingNo\":\"14156774\",\"ExternalTradingNo\":null}],\"Summary\":{\"OrderId\":112507902,\"PaidCash\":30.00,\"PaidGift\":0.00,\"PaidFreeCard\":0.00,\"PaidYmtCoupon\":1.00,\"PaidSellerCoupon\":0.00,\"PostPaidCash\":0.00,\"PostPaidGift\":0.00,\"TotalThirdPartyDiscount\":0.0,\"TotalProductPrice\":10.00,\"FirstPayProductPrice\":10.00,\"Freight\":21.00,\"OrderDiscount\":0.00,\"PostPayDiscount\":0.00,\"TotalRefundedCash\":null,\"TotalRefundedGift\":null,\"TotalRefundedYmtCoupon\":null,\"TotalActivityPrice\":0.00,\"TotalCanceledCash\":null,\"TotalCanceledYmtCoupon\":null,\"TotalRefundedThirdPartyDiscount\":0.0}},\"Transfer\":{\"DeliveredTime\":null,\"ReceiptConfirmedTime\":null}}]},\"Trace\":{\"Key\":\"22f07a9a180b4a24a4be5d140d2dc716\",\"ExecutionMilliseconds\":195}}");
		*/System.out.println(BigDecimal.ZERO.setScale(2));
	}
}
